Component({
  options: {
    multipleSlots: true
  },
  properties: {
    showDay: { // 是否显示天
      type: Boolean,
      value: false
    },
    endDate: { // 结束日期
      type: String,
      value: ''
    },
    fontSize: { // 日期字体大小
      type: [Number, String],
      value: 14
    },
    size: { // 计时框尺寸大小
      type: [Number, String],
      value: 24
    },
    bgColor: { // 背景颜色
      type: String,
      value: '#3565ee'
    },
    color: { // 文本颜色
      type: String,
      value: '#fff'
    },
  },
  data: {
    days: 0,
    hours: '00',
    minutes: '00',
    seconds: '00',
    timer: -1
  },
  lifetimes: {
    attached: function () {
    },
  },
  observers: {
    'endDate': function (newVal) {
      clearInterval(this.data.timer);
      if (!newVal) return;
      this.init();
    }
  },
  methods: {
    //初始化
    init() {
      let endDate = this.data.endDate.replace(/-/g, '/');
      let endTime = new Date(endDate).getTime();
      let nowTime = new Date().getTime();
      let leftTime = parseInt((endTime - nowTime) / 1000);
      this.setData({
        leftTime:endTime
      })
      if (leftTime <= 0) return;
      this.data.timer = setInterval(() => {
        if (leftTime <= 0) {
          this.triggerEvent('end');
          clearInterval(this.data.timer);
        }
        this.setCountDown(leftTime);
        leftTime -= 1;
      }, 1000)
    },
    //计算时间
    setCountDown(leftTime) {
      let d = parseInt(leftTime / (24 * 60 * 60));
      let h = this.formate(parseInt(leftTime / (60 * 60) % 24));
      let m = this.formate(parseInt(leftTime / 60 % 60));
      let s = this.formate(parseInt(leftTime % 60));
      this.setData({
        days: d,
        hours: h,
        minutes: m,
        seconds: s
      })
    },
    //时间格式化
    formate(time) {
      if (time >= 10) {
        return time
      } else {
        return `0${time}`
      }
    }
  }
})
